package com.lighting.common.feign.search.listener;

import com.lighting.common.feign.search.annotation.SearchDocument;
import com.lighting.common.feign.search.annotation.SearchField;
import com.lighting.common.feign.search.constant.SearchConstant;
import com.lighting.common.feign.search.util.SearchUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SearchFeignApplicationListener implements CommandLineRunner {

    public static boolean open = true;
    @Resource
    private ApplicationContext applicationContext;

    @Override
    public void run(String... args) throws Exception {
        if (!open) {
            return;
        }
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(SearchDocument.class);
        for (Object index : beans.values()) {
            SearchDocument searchDocument = SearchUtil.getAnnotation(index.getClass(), SearchDocument.class);
            Map<String, String> properties = this.getProperties(index.getClass());
            SearchConstant.indexProperty.put(searchDocument.indexName(), properties);
        }
    }

    private Map<String, String> getProperties(Class<?> clazz) {
        Map<String, String> properties = clazz.getSuperclass() != null ? this.getProperties(clazz.getSuperclass()) : new HashMap<>();
        for (Field field : clazz.getDeclaredFields()) {
            SearchField searchField = field.getAnnotation(SearchField.class);
            if (searchField == null || StringUtils.isEmpty(searchField.name())) {
                properties.put(field.getName(), null);
                continue;
            }
            properties.put(field.getName(), searchField.name());
        }
        return properties;
    }
}
